﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.Entity;

public partial class masterdata_Chain_Customer : PageBase
{
    private const string CHAIN_ID = "id";
    private decimal chainID = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request[CHAIN_ID]))
            decimal.TryParse(Request[CHAIN_ID], out chainID);

        if (!IsPostBack)
        {
            InitForm();
            BindGrid();
        }
    }

    #region 数据绑定
    private void InitForm()
    {
        Jumpton.Persistent.ObjectTable ot;

        //绑定当前登录的部门
        txtHidOrg.Value = string.Format("'{0}'",MyStateManager.OrgID);
        txtOrg.Text = new OrgainzationManager().Load(MyStateManager.OrgID).NAME;

        //根据当前的部门得到下面的经销商
        OrgHelper.BindChiansDDL(MyStateManager.DomainID, txtHidOrg.Value, ddlChains);
        ddlChains.SelectedValue = chainID.ToString();

        //绑定客户渠道
        DictionaryItemsManager dim = new DictionaryItemsManager();
        ddlChannel.DataTextField = "Name";
        ddlChannel.DataValueField = "DictionaryItemId";
        ddlChannel.DataSource = dim.GetItemList(DictionaryEnum.CustomerChannel, this.MyStateManager.DomainID);
        ddlChannel.DataBind();
        ddlChannel.Items.Insert(0, new ListItem(Resources.language.ddl_All, ""));

        lblChain.Text = new ChainManager().Load(int.Parse(chainID.ToString())).DESCRIPTION;

    }
    #endregion

    protected void btnQuery_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

    #region 绑定查询数据
    public DataTable BindGrid()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        if (txtHidOrg.Value != string.Empty)
        {
            sb.Append(string.Format(" AND C.ORG_ID IN ({0})", txtHidOrg.Value));

        }

        if (txtCustomer.Text != string.Empty)
        {
            sb.Append(" AND C.[NAME] LIKE '%" + txtCustomer.Text.Trim() + "%'");
        }

        if (ddlChains.SelectedValue != string.Empty)
        {
            sb.Append(" And CHAINS.ID = '" + ddlChains.SelectedValue + "' ");
        }
        if (ddlChannel.SelectedValue != string.Empty)
        {
            sb.Append(" AND LOCAL_LEVEL1_CODE =  '" + ddlChannel.SelectedValue + "'  ");
        }

        if (ddlStatus.SelectedValue=="1")
            sb.Append(" AND #TMP.ID IS NOT NULL");
        else if(ddlStatus.SelectedValue=="0")
            sb.Append(" AND #TMP.ID IS NULL");

        DataSet ds = CustomerManager.SearchCustomerIncludeChain(chainID,sb.ToString());
        if (ds != null && ds.Tables.Count > 0)
        {
            gvCustomerList.DataSource = ds;
            gvCustomerList.DataBind();
        }

        return ds.Tables[0];
    }
    #endregion


    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        ddlChains.Items.Clear();

        if (!string.IsNullOrEmpty(txtHidChains.Value))
        {
            string[] options = txtHidChains.Value.Split('∮');

            for (int i = 0; i < options.Length; i++)
            {
                string[] item = options[i].Split('∞');
                ddlChains.Items.Add(new ListItem(item[1], item[0]));
            }
        }
        ddlChains.Items.Insert(0, new ListItem("--所有--", ""));
    }

    protected void gvCustomerList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvCustomerList.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void btnSubmiet_Click(object sender, EventArgs e)
    {
        decimal customerID = 0;

        //该门店是否已经属于经销商
        bool include;

        //是否选择
        CheckBox cbx;
        CUSTOMER_CHAINS customerChain;

        //遍历每一行
        foreach (GridViewRow row in gvCustomerList.Rows)
        {
            decimal.TryParse(gvCustomerList.DataKeys[row.RowIndex].Values["ID"].ToString(), out customerID);
            include = Convert.ToBoolean(gvCustomerList.DataKeys[row.RowIndex].Values["INCLUDE"].ToString());
            cbx=(CheckBox)row.FindControl("cbxSelected");

            //插入挂接新的门店
            if (cbx.Checked && !include)
            {
                customerChain = new CUSTOMER_CHAINS();
                customerChain.CUSTOMERID = customerID;
                customerChain.CHAINSID = int.Parse(chainID.ToString());
                customerChain.DOMAINID = MyStateManager.DomainID;
                customerChain.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
                customerChain.LAST_UPDATER = MyStateManager.Name;
                customerChain.Save();

                continue;
            }

            //删除已挂接的门店
            if (!cbx.Checked && include)
            {
                customerChain = new ChainManager().LoadCustomerChain(customerID, chainID);
                if (customerChain != null)
                    customerChain.Delete();

                continue;
            }

        }

        Response.Redirect("Chain_List.aspx");
    }
    protected void btnAllInclude_Click(object sender, EventArgs e)
    {
        Save(false);
    }

    #region 批量提交
    protected void Save(bool cancel)
    {
        CUSTOMER_CHAINS customerChain = new CUSTOMER_CHAINS();
        DataTable dt = BindGrid();

        foreach (DataRow row in dt.Rows)
        {
            if (cancel)
            {
                if (Convert.ToBoolean(row["INCLUDE"]))
                {
                    customerChain = new ChainManager().LoadCustomerChain(decimal.Parse(row["ID"].ToString()), chainID);
                    if (customerChain != null)
                        customerChain.Delete();
                }

            }
            else
            {
                if (!Convert.ToBoolean(row["INCLUDE"]))
                {
                    customerChain = new CUSTOMER_CHAINS();
                    customerChain.CUSTOMERID = decimal.Parse(row["ID"].ToString());
                    customerChain.CHAINSID = int.Parse(chainID.ToString());
                    customerChain.DOMAINID = MyStateManager.DomainID;
                    customerChain.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
                    customerChain.LAST_UPDATER = MyStateManager.Name;
                    customerChain.Save();
                }
            }
        }

        Response.Redirect("Chain_List.aspx");
    }

    #endregion

    protected void btnAllUninclude_Click(object sender, EventArgs e)
    {
        Save(true);
    }
}
